import time
import xlwings


def write_result_to_excel(cell, result):
    '''
    write the test result to excel report
    :param cell: Excel 单元格， 如：“C8”
    :param result: 测试结果：“pass”, "fail"
    :return: None
    '''
    try:

        app = xlwings.App(visible=True, add_book=False)  # 程序可见，只打开不新建工作薄
        app.display_alerts = False  # 警告关闭
        app.screen_updating = False  # 屏幕更新关闭
        xlsx_path = "MOPC-XXX_Virtual-Physical DeviceTestResult.xlsx"
        workbook = app.books.open(xlsx_path)

        # 写入测试日期，格式：年月日
        data = workbook.sheets('Sheet1').range(cell)
        data.value = result

        # 获取颜色
        sheet = workbook.sheets('Sheet1')
        print(sheet.range(cell).color)
        # 设置颜色
        sheet.range(cell).color = (255, 0, 0)
        # sheet.range('C1').color = (255, 0, 120)
        # 清除颜色
        # sheet.range('C1').color = None
    except Exception as e:
        print("Write excel report occur exception！")
        workbook.close()  # 关闭文件
        app.quit()  # 关闭程序
        time.sleep(5)
    else:  # try中没有引发异常则执行else语句
        print("Write excel report not have exception, 保存退出！")
        workbook.save()  # 保存文件
        workbook.close()  # 关闭文件
        app.quit()  # 关闭程序
        time.sleep(5)
    finally:
        print("write excel report finish.")
        # for process in wmi.WMI().Win32_Process():  # 遍历所有进程，时间要好几秒
        #     # print(process.ProcessId, process.Name)
        #     # process_list.append(process.Name)   # 将所有进程写入列表
        #     # with open("process_list.txt", "w") as f:  # 将进程列表写入文件。每次写入会覆盖原有内容
        #     #     f.writelines(process_list)
        #     if (process.Name == "EXCEL.EXE"):
        #         process.Terminate()  # 遍历所有进程，如果有MO进程则终止进程


if __name__ == "__main__":
    write_result_to_excel("C8")

